<template>
	<view class="goods-manage-container">
		<!-- 搜索和筛选区 -->
		<view class="search-filter">
			<view class="search-box">
				<uni-icons type="search" size="16" color="#666"></uni-icons>
				<input type="text" v-model="searchKey" placeholder="搜索商品名称" />
			</view>
			<view class="filter-btn" @tap="showCategoryFilter">
				<text>{{ currentCategory ? currentCategory.name : '全部分类' }}</text>
				<uni-icons type="bottom" size="12" color="#666"></uni-icons>
			</view>
		</view>

		<!-- 分类支付方式提示 -->
		<view class="payment-type-alert" v-if="currentCategory && currentCategory.paymentType">
			<uni-icons type="info" size="16" color="#2979ff"></uni-icons>
			<text>当前分类支持的支付方式：{{ getPaymentTypeText(currentCategory.paymentType) }}</text>
		</view>

		<!-- 状态标签 -->
		<view class="status-tabs">
			<view v-for="(item, index) in statusList" :key="index"
				:class="['tab-item', currentStatus === index ? 'active' : '']" @tap="switchStatus(index)">
				<text>{{ item.name }}</text>
				<text class="count">({{ formatCount(item.count) }})</text>
			</view>
		</view>

		<!-- 商品列表 -->
		<scroll-view scroll-y class="goods-list" @scrolltolower="loadMore" refresher-enabled
			:refresher-triggered="isRefreshing" @refresherrefresh="onRefresh">
			<view class="goods-item" v-for="(goods, index) in goodsList" :key="index">
				<view class="goods-basic">
					<image :src="goods.mainImages[0].imageUrl" mode="aspectFill" class="goods-image"></image>
					<view class="goods-info">
						<view class="goods-name">{{ goods.name }}</view>
						<view class="goods-price" v-if="goods.paymentType === 1">
							<text class="price">{{ goods.price }}</text>
						</view>
						<view class="goods-price" v-if="goods.paymentType === 2">
							<text class="points">{{ goods.points }}积分</text>
						</view>
						<view class="goods-status">
							<text :class="['status-tag', getStatusClass(goods.status)]">
								{{ goods.status === 1 ? '已上架' : '已下架' }}
							</text>
							<text :class="['audit-tag', getAuditClass(goods.auditStatus)]">
								{{ getAuditText(goods.auditStatus) }}
							</text>
						</view>
					</view>
				</view>

				<view class="goods-data">
					<view class="data-item">
						<text class="label">库存</text>
						<text class="value formatted">{{ formatNumber(goods.stock) }}</text>
					</view>
					<view class="data-item">
						<text class="label">销量</text>
						<text class="value formatted">{{ formatNumber(goods.sales) }}</text>
					</view>
				</view>

				<view class="action-buttons">
					<button class="btn outline" @tap="editGoods(goods)">编辑</button>
					<button class="btn" :class="goods.status === 1 ? 'danger' : ''" @tap="toggleGoodsStatus(goods)" 
						:disabled="goods.auditStatus !== 1 && goods.status === 0">
						{{ goods.status === 1 ? '下架' : '上架' }}
					</button>
				</view>
			</view>

			<!-- 添加底部加载状态 -->
			<view class="loading-more" v-if="goodsList.length > 0">
				<text v-if="loading">加载中...</text>
				<text v-else-if="!hasMore">没有更多了</text>
			</view>
		</scroll-view>

		<!-- 分类选择器 -->
		<uv-picker ref="categoryPicker" :columns="[categoryColumns]" :loading="loading" @confirm="onCategoryConfirm"
			@cancel="onCategoryCancel" @change="onCategoryChange" keyName="name" closeOnClickOverlay
			title="选择分类"></uv-picker>
	</view>
</template>

<script>
export default {
	data() {
		return {
			searchKey: '',
			currentStatus: 0,
			currentCategory: null,
			statusList: [
				{ name: '全部', count: 0 },
				{ name: '已上架', count: 0 },
				{ name: '已下架', count: 0 },
				{ name: '待审核', count: 0 },
				{ name: '已拒绝', count: 0 }
			],
			goodsList: [],
			categoryList: [],
			enabledCategoryList: [],
			pageNum: 1,
			pageSize: 10,
			hasMore: true,
			loading: false,
			isRefreshing: false,
			total: 0,
			categoryColumns: [],
			merchantId: null,
			searchTimer: null
		}
	},
	methods: {
		switchStatus(index) {
			this.currentStatus = index;
			this.pageNum = 1;
			this.hasMore = true;
			this.getGoodsList();
		},

		async fetchCategory() {
			try {
				this.loading = true;
				const data = await this.$http.get('/mall/category/all');

				if (Array.isArray(data)) {
					this.categoryList = data.sort((a, b) => (a.sort || 0) - (b.sort || 0));
					this.enabledCategoryList = this.categoryList.filter(item => item.status === 1);

					if (this.currentCategory && !this.enabledCategoryList.find(item => item.id === this.currentCategory.id)) {
						uni.showModal({
							title: '分类状态变更提醒',
							content: `分类"${this.currentCategory.name}"已被系统禁用，该分类下的商品将自动下架。`,
							showCancel: false,
							success: () => {
								this.currentCategory = null;
								this.getGoodsList();
							}
						});
					}
				} else {
					uni.showToast({
						title: '分类数据格式错误',
						icon: 'none'
					});
				}
			} catch (e) {
				uni.showToast({
					title: '获取分类失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},

		showCategoryFilter() {
			if (!this.categoryList || !this.categoryList.length) {
				uni.showToast({
					title: '暂无分类数据',
					icon: 'none'
				});
				return;
			}

			this.categoryColumns = [
				{
					name: '全部分类',
					id: null,
					status: 1
				},
				...this.categoryList.map(item => ({
					...item,
					name: item.name + (item.status === 0 ? ' (已禁用)' : '')
				}))
			];

			this.$refs.categoryPicker.open();
		},

		onCategoryConfirm(e) {
			const selectedItem = e.value[0];

			if (!selectedItem.id) {
				this.currentCategory = null;
			} else if (selectedItem.status === 0) {
				uni.showModal({
					title: '提示',
					content: '该分类已被系统禁用，所属商品将无法上架。',
					showCancel: false
				});
				return;
			} else {
				this.currentCategory = selectedItem;
			}

			this.pageNum = 1;
			this.hasMore = true;
			this.getGoodsList();
		},

		getPaymentTypeText(paymentType) {
			if (!paymentType) return '';

			const typeMap = {
				'1': '现金',
				'2': '积分',
				'3': '积分+现金',
				'4': '礼品卡',
				'5': '礼品券'
			};

			try {
				const types = String(paymentType).split(',');
				return types
					.map(type => typeMap[type.trim()])
					.filter(Boolean)
					.join('/');
			} catch (e) {
				return '';
			}
		},

		async getGoodsList(isLoadMore = false) {
			if (this.loading) return;

			try {
				this.loading = true;

				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					name: this.searchKey || undefined,
					categoryId: this.currentCategory?.id || 0,
					merchantId: Number(this.merchantId),
					...this.getStatusParams()
				};

				const data = await this.$http.post('/mall/goods/merchant/list', params);
				if (data) {
					
					if (isLoadMore) {
						this.goodsList = [...this.goodsList, ...data.items];
					} else {
						this.goodsList = data.items;
					}

					this.total = data.count;
					this.hasMore = this.goodsList.length < data.count;
				}
			} catch (e) {
				uni.showToast({
					title: '获取商品列表失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				if (this.isRefreshing) {
					this.isRefreshing = false;
					uni.stopPullDownRefresh();
				}
			}
		},

		getStatusParams() {
			switch (this.currentStatus) {
				case 0: // 全部
					return {};
				case 1: // 已上架
					return { status: 1 };
				case 2: // 已下架
					return { status: 0 };
				case 3: // 待审核
					return { auditStatus: 0 };
				case 4: // 已拒绝
					return { auditStatus: 2 };
				default:
					return {};
			}
		},

		loadMore() {
			if (!this.hasMore || this.loading) return;

			this.pageNum++;
			this.getGoodsList(true);
		},

		onRefresh() {
			this.isRefreshing = true;
			this.pageNum = 1;
			this.hasMore = true;
			this.getGoodsList();
		},

		getAuditText(status) {
			const map = {
				0: '待审核',
				1: '已通过',
				2: '已拒绝'
			};
			return map[status] || '';
		},

		getAuditClass(status) {
			const map = {
				0: 'pending',
				1: 'approved',
				2: 'rejected'
			};
			return map[status] || '';
		},

		getStatusClass(status) {
			return status === 1 ? 'on-shelf' : 'off-shelf';
		},

		onCategoryCancel() {
			// 取消选择时的处理
		},

		onCategoryChange(e) {
			// 选择变化时的处理
			// e.value 是当前选中的值
			// e.index 是当前选中的索引
		},

		initMerchantId() {
			const merchantId = Number(this.$route.query.merchantId || this.$route.params.merchantId);
			if (!merchantId) {
				uni.showToast({
					title: '缺少商家ID参数',
					icon: 'none'
				});
				// 可以选择返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
				return;
			}
			this.merchantId = merchantId;
		},

		// 获取状态统计数据
		async fetchStatusCount() {
			try {
				const data = await this.$http.get(`/mall/goods/status/count?merchantId=${this.merchantId}`);

				if (data) {
					// 更新状态列表数量
					this.statusList = [
						{ name: '全部', count: data.total || 0 },
						{ name: '已上架', count: data.onShelf || 0 },
						{ name: '已下架', count: data.offShelf || 0 },
						{ name: '待审核', count: data.pending || 0 },
						{ name: '已拒绝', count: data.rejected || 0 }
					];
				}
			} catch (e) {
				uni.showToast({
					title: '获取统计数据失败',
					icon: 'none'
				});
			}
		},

		formatNumber(num) {
			if (!num && num !== 0) return '0';
			return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
		},

		formatCount(count) {
			return count > 99 ? '99+' : count;
		},

		// 编辑商品
		editGoods(goods) {
			uni.navigateTo({
				url: `/subpkg/edit_goods/edit_goods?id=${goods.id}&merchantId=${this.merchantId}`
			});
		},

		// 切换商品上架/下架状态
		async toggleGoodsStatus(goods) {
			const action = goods.status === 1 ? '下架' : '上架';
			const isOnSale = goods.status === 1;

			// 如果是上架操作，检查商品审核状态
			if (!isOnSale) {
				// 检查商品审核状态
				if (goods.auditStatus !== 1) {
					let content = '该商品未通过审核，无法上架';
					if (goods.auditStatus === 0) {
						content = '该商品正在审核中，请等待审核通过后再上架';
					} else if (goods.auditStatus === 2) {
						content = '该商品审核未通过，请修改后重新提交审核';
					}
					uni.showModal({
						title: '无法上架',
						content: content,
						showCancel: false
					});
					return;
				}
			}

			uni.showModal({
				title: '确认操作',
				content: `确定要${action}该商品吗？`,
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({
								title: `${action}中...`
							});

							// 根据操作类型调用不同的接口
							const url = isOnSale ? '/mall/goods/off-sale' : '/mall/goods/on-sale';
							
							await this.$http.post(url, {
								goodsId: goods.id
							}, {
								header: {
									'Content-Type': 'application/x-www-form-urlencoded'
								}
							});

							uni.hideLoading();
							uni.showToast({
								title: `${action}成功`,
								icon: 'success'
							});

							// 更新本地数据
							goods.status = isOnSale ? 0 : 1;

							// 刷新状态统计
							await this.fetchStatusCount();

						} catch (e) {
							uni.hideLoading();
							// 根据错误信息显示具体的错误提示
							let errorMsg = `${action}失败`;
							if (e && e.msg) {
								errorMsg = e.msg;
							} else if (e && e.message) {
								errorMsg = e.message;
							}
							uni.showToast({
								title: errorMsg,
								icon: 'none'
							});
						}
					}
				}
			});
		},

		// 防抖搜索
		debounceSearch() {
			clearTimeout(this.searchTimer);
			this.searchTimer = setTimeout(() => {
				this.pageNum = 1;
				this.hasMore = true;
				this.getGoodsList();
			}, 500);
		}
	},

	watch: {
		searchKey() {
			this.debounceSearch();
		}
	},

	async onLoad(options) {
		// 从路由参数中获取 merchantId
		this.merchantId = Number(options.merchantId);
		if (!this.merchantId) {
			uni.showToast({
				title: '缺少商家ID参数',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
			return;
		}

		// 初始化其他数据
		await this.fetchCategory();
		await this.getGoodsList();

		// 获取状态统计
		await this.fetchStatusCount();
	},

	async onPullDownRefresh() {
		this.pageNum = 1;
		this.hasMore = true;
		await this.getGoodsList();
		uni.stopPullDownRefresh();
	}
}


</script>

<style lang="scss" scoped>
@import 'merchant_goods_manage.scss';

.loading-more {
	text-align: center;
	padding: 20rpx 0;
	color: #999;
	font-size: 24rpx;
}
</style>